package com.woniuxy.qiantai.interceptors;

import com.woniuxy.qiantai.utils.CookieUtils;
import com.woniuxy.qiantai.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //使用拦截器进行token续期
        //获取到cookie中的token
        String userToken2Cookie = CookieUtils.getUserToken2Cookie(request);
        if (!StringUtils.isEmpty(userToken2Cookie)){
            try {
                //如果token过期 JwtUtils.getAccount(userToken2Cookie);会报错
                String account = JwtUtils.getAccount(userToken2Cookie);
            } catch (Exception e) {
              //对token进行续期
                //从Redis中取出account账号
                String redisAccount = stringRedisTemplate.opsForValue().get(userToken2Cookie);
                //重新生成token
                String refreshToken = JwtUtils.createToken(redisAccount, 15);
                //将新的token存入 cookie中
                CookieUtils.setUserToken2Cookie(response,refreshToken);
                //同步更新Redis中的数据
                stringRedisTemplate.delete(userToken2Cookie);
                stringRedisTemplate.opsForValue().set(refreshToken,redisAccount,30, TimeUnit.MINUTES);
                System.out.println("token续期"+refreshToken);
            }
        }
        //如果userToken2Cookie为null 表示用户还没有登录 直接放行
        return true;
    }
}
